# Bartender.py
import os
import sys
import clr  # 先安装`pythonnet`
import decorator

FolderPath = os.getcwd()  # 获取当前路径
sys.path.append(FolderPath)  # 加载当前路径
clr.FindAssembly("Seagull.BarTender.Print.dll")
clr.AddReference("Seagull.BarTender.Print")
from Seagull.BarTender.Print import Engine, Printers, Printer, LabelFormatDocument, Messages, Message, SaveOptions


class BarTender():  #
    """创建打印机类方便在上位机主程序中调用"""

    def __init__(self):
        """
        启用引擎
        """
        self.btEngine = Engine(True)
        printerList, self.printerName = self.get_printer_list()
        print("打印机列表：", printerList, "\n默认打印机：", self.printerName)

    def get_printer_list(self):
        """
        获取你电脑上的打印机列表
        :return: list str 打印机列表和默认打印机名称
        """
        printers = Printers()  # 获取打印机列表
        printer_list = []
        for printer in printers:
            printer_list.append(printer.PrinterName)
        return printer_list, printers.Default.PrinterName

    def start_engine(self):
        """启动打印引擎"""
        if self.btEngine.IsAlive:
            return
        self.btEngine.Start()

    @decorator.timer  # 计算函数运行时间
    def creat_task(self, filePath: str, data: dict):
        """
        创建打印任务
        :param filePath:  bartender导出的btw标签文件路径
        :return:
        """
        self.start_engine()
        # 打开格式文档
        self.btFormat = self.btEngine.Documents.Open(filePath)
        # 选择打印机
        self.btFormat.PrintSetup.PrinterName = b.printerName
        self.set_data_dict(data)
        # 打印格式文档
        Result = self.btFormat.Print()  # 'Success' 代表发送给了打印机
        # 关闭当前格式而不保存。
        self.btFormat.Close(SaveOptions.DoNotSaveChanges)
        # 停止打印引擎
        #self.btEngine.Stop()

    def get_data_dict(self, key=None):
        """获取你的标签文件.btw的内容"""
        data_dict = {}
        if self.btFormat:
            if key:
                return self.btFormat.SubStrings[key].Value
            for substring in self.btFormat.SubStrings:
                data_dict[substring.Name] = substring.Value
        return data_dict

    def set_data_dict(self, data_dict):
        """
        通过字典修改标签.btw文件中的数据源内容
        :param data_dict: {'num':'11111'}则会把表的num变量的值设置为11111
        :return:
        """
        if not len(data_dict) and not self.btFormat:
            return
        for key, value in data_dict.items():
            for substring in self.btFormat.SubStrings:
                if substring.Name == key:
                    self.btFormat.SubStrings.SetSubString(key, value)

    def __del__(self):
        """关闭引擎，释放资源"""
        if self.btEngine.IsAlive:
            # self.btEngine.Stop()
            # self.btEngine.Dispose()
            pass


if __name__ == "__main__":
    os.getcwd()
    b = BarTender()
    b.get_printer_list()
    # key:为在bartender中命名的嵌入数据源，value:为你想设定到标签内的嵌入数据
    s = {'model': '2UEW/180', 'qr': 'so145!@$^*##%& !@%5', 'id': '1234567890ABCD', 'date': '2024/7/6 14:36:00',
         'workers': '321'}
    b.creat_task(filePath=os.getcwd() + r"\label02.btw", data=s)  # 注意会阻塞线程